﻿using Client.IBLL;
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace Client.Start.ViewModels {
  public class LoginViewModel :BindableBase{
    private string _userName="admin";
    ILoginBLL _loginBLL;
    public LoginViewModel(ILoginBLL loginBLL) {
      _loginBLL = loginBLL;
    }

    public string UserName{
      get { return _userName; }
      set { SetProperty<string>(ref _userName, value); }
    }

    private string _password="123456";

    public string Password{
      get { return _password; }
      set { SetProperty<string>(ref _password, value); }
    }
    private string _errorMsg;

    public string ErrorMsg {
      get { return _errorMsg; }
      set { SetProperty<string>(ref _errorMsg, value); }
    }


    //登录命令
    public ICommand LoginCommand {
      get => new DelegateCommand<object>(OnLogin);
    }
    private void OnLogin(object obj) {
      try {
        ErrorMsg = "";
        if (string.IsNullOrEmpty(UserName)) {
          throw new Exception("请输入用户名");
        }
        if (string.IsNullOrEmpty(Password)) {
          throw new Exception("请输入密码");
        }
        //登录操作
        if (_loginBLL.Login(UserName, Password).GetAwaiter().GetResult()) {
          //关闭登录窗口
          (obj as Window).DialogResult = true;
        } else {
          throw new Exception("用户名或密码错误");
        }
      }catch(Exception e) {
        this.ErrorMsg ="登录失败！"+e.Message;
      }
    }

  }
}
